<template>
  <div>
    <el-row :gutter="24">
      <el-col :span="3">
        <el-input
          class="filterInput"
          clearable
          placeholder="请输入分类名称"
          v-model="filterCategoryName"
        >
        </el-input>
        <el-tree
          :highlight-current="true"
          ref="tree"
          :data="treeData"
          :props="treeProps"
          node-key="id"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          @node-click="selectedCategory"
        ></el-tree
      ></el-col>
      <el-col :span="6">
        <el-row type="flex" class="row-bg" justify="space-between">
          <el-col :span="18">
            <el-tag>选中分类：{{ selectedCategoryName }}</el-tag>
          </el-col>
          <el-col :span="6" class="table-tools">
            <el-button
              :disabled="selectedCategoryId == null"
              icon="el-icon-plus"
              type="primary"
              @click="openGroupDialog()"
              v-if="hasPermission(permission.save)"
              >添加</el-button
            >
          </el-col>
        </el-row>
        <el-table
          ref="groupTable"
          :highlight-current-row="true"
          border
          :data="groupTableData"
          style="width: 100%"
          @row-click="selectedGroup"
        >
          <el-table-column prop="name" label="分组名称" />
          <!-- 操作 -->
          <el-table-column label="操作" width="170" v-if="hasAnyPermission()">
            <template slot-scope="scope">
              <div class="btnOperateList">
                <el-button
                  type="text"
                  size="medium"
                  icon="el-icon-top"
                  :disabled="scope.$index == 0"
                  @click="groupSortUp(scope.$index)"
                  v-if="hasPermission(permission.update)"
                ></el-button>
                <el-button
                  type="text"
                  size="medium"
                  icon="el-icon-bottom"
                  :disabled="scope.$index == groupTableData.length - 1"
                  @click="groupSortDown(scope.$index)"
                  v-if="hasPermission(permission.update)"
                ></el-button>

                <!-- 编辑 -->
                <el-button
                  type="text"
                  size="medium"
                  icon="el-icon-edit"
                  @click="openGroupDialog(scope.row)"
                  v-if="hasPermission(permission.update)"
                ></el-button>

                <!-- 删除 -->
                <el-button
                  type="text"
                  size="medium"
                  icon="el-icon-delete"
                  @click="deleteGroupRow(scope.row)"
                  v-if="hasPermission(permission.delete)"
                ></el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="15">
        <el-row type="flex" class="row-bg" justify="space-between">
          <el-col :span="18">
            <el-tag>选中分组：{{ selectedGroupName }}</el-tag>
          </el-col>
          <el-col :span="6" class="table-tools">
            <el-button
              type="primary"
              :disabled="selectedGroupId == null"
              icon="el-icon-plus"
              @click="openAttrDialog()"
              v-if="hasPermission(permission.save)"
              >添加</el-button
            >
          </el-col>
        </el-row>
        <el-table
          ref="attrTable"
          :highlight-current-row="true"
          border
          :data="attrTableData"
          style="width: 100%"
        >
          <el-table-column prop="name" label="属性名称" width="180" />
          <el-table-column prop="typeName" label="属性类型" width="110">
            <template slot-scope="{ row }">
              <div class="attrType">
                <el-tag v-if="row.isSearch == 1" type="success"
                  >支持检索</el-tag
                >
                <el-tag v-if="row.isMulti == 1" type="warning">多值类型</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="dataTypeName" label="数据类型" width="90">
            <template slot-scope="{ row }">
              <el-tag v-if="row.dataType == 0" type="success">{{
                row.dataTypeName
              }}</el-tag>
              <el-tag v-if="row.dataType == 1" type="info">{{
                row.dataTypeName
              }}</el-tag>
              <el-tag v-if="row.dataType == 2" type="warning">{{
                row.dataTypeName
              }}</el-tag>
              <el-tag v-if="row.dataType > 2" type="warning">{{
                row.dataTypeName
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="options"
            label="可选项"
            :show-overflow-tooltip="true"
          >
            <template
              slot-scope="scope"
              v-if="scope.row.optionList != '' && scope.row.optionList != null"
            >
              <el-tag
                class="options-tag"
                type="info"
                v-for="(option, index) in scope.row.optionList"
                :key="index"
              >
                {{ option.attrValue + "" + scope.row.unit }}
              </el-tag>
            </template>
          </el-table-column>
          <!-- 操作 -->
          <el-table-column label="操作" width="170" v-if="hasAnyPermission()">
            <template slot-scope="scope">
              <div class="btnOperateList">
                <el-button
                  type="text"
                  size="medium"
                  icon="el-icon-top"
                  :disabled="scope.$index == 0"
                  @click="attrSortUp(scope.$index)"
                  v-if="hasPermission(permission.update)"
                ></el-button>
                <el-button
                  type="text"
                  size="medium"
                  icon="el-icon-bottom"
                  :disabled="scope.$index == attrTableData.length - 1"
                  @click="attrSortDown(scope.$index)"
                  v-if="hasPermission(permission.update)"
                ></el-button>

                <!-- 编辑 -->
                <el-button
                  type="text"
                  size="medium"
                  icon="el-icon-edit"
                  @click="openAttrDialog(scope.row)"
                  v-if="hasPermission(permission.update)"
                ></el-button>

                <!-- 删除 -->
                <el-button
                  type="text"
                  size="medium"
                  icon="el-icon-delete"
                  @click="deleteAttrRow(scope.row)"
                  v-if="hasPermission(permission.delete)"
                ></el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <UpdateGroup
      ref="updateGroupDialog"
      :dialogTitle="groupDialogTitle"
    ></UpdateGroup>
    <UpdateAttr
      ref="updateAttrDialog"
      :dialogTitle="attrDialogTitle"
    ></UpdateAttr>
  </div>
</template>

<script>
import { mapState } from "vuex";

// 请求接口 start
import UpdateGroup from "@/views/product/baseAttr/updateGroup";
import UpdateAttr from "@/views/product/baseAttr/updateAttr";
import productApi from "@/api/productApi";
// 请求接口 end

export default {
  name: "productBaseAttr",
  components: {
    UpdateGroup,
    UpdateAttr,
  },
  data() {
    return {
      permission: {
        save: "product:baseAttr:save",
        update: "product:baseAttr:update",
        delete: "product:baseAttr:delete",
      },
      // 数据 start
      groupDialogTitle: "属性分组",
      attrDialogTitle: "属性",

      // 分类树信息
      treeProps: {
        children: "children",
        label: "name",
      },
      filterCategoryName: "",

      // 选中的分类ID
      selectedCategoryId: null,
      selectedCategoryName: "",

      // 选中的分组ID
      selectedGroupId: null,
      selectedGroupName: "",

      // 分类列表数据
      treeData: [],

      // 分组列表和属性列表
      groupTableData: [],
      attrTableData: [],
    };
  },
  created() {
    this.remoteCategoryTreeList();
  },
  watch: {
    filterCategoryName(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    groupSortUp(index) {
      if (index > 0) {
        productApi.group
          .swapSort(
            this.groupTableData[index - 1].id,
            this.groupTableData[index].id
          )
          .then((res) => {
            this.resetGroupList();
            this.clearSelectedGroupInfo();
          })
          .catch((error) => {});
      }
    },
    groupSortDown(index) {
      if (index < this.groupTableData.length - 1) {
        productApi.group
          .swapSort(
            this.groupTableData[index].id,
            this.groupTableData[index + 1].id
          )
          .then((res) => {
            this.resetGroupList();
            this.clearSelectedGroupInfo();
          })
          .catch((error) => {});
      }
    },
    attrSortUp(index) {
      if (index > 0) {
        productApi.baseAttr
          .swapSort(
            this.attrTableData[index - 1].id,
            this.attrTableData[index].id
          )
          .then((res) => {
            this.resetAttrList();
          })
          .catch((error) => {});
      }
    },
    attrSortDown(index) {
      if (index < this.groupTableData.length - 1) {
        productApi.baseAttr
          .swapSort(
            this.attrTableData[index].id,
            this.attrTableData[index + 1].id
          )
          .then((res) => {
            this.resetAttrList();
          })
          .catch((error) => {});
      }
    },
    // 权限判断
    hasPermission(permission) {
      return this.user.permissionArr.includes(permission);
    },
    // 权限判断
    hasAnyPermission() {
      for (var key in this.permission) {
        if (
          key != "save" &&
          this.user.permissionArr.includes(this.permission[key])
        ) {
          return true;
        }
      }
      return false;
    },
    // 刷新分组
    resetGroupList() {
      this.remoteGroupList(this.selectedCategoryId);
    },
    // 刷新属性
    resetAttrList() {
      this.remoteAttrList(this.selectedGroupId);
    },
    // 打开分组弹窗
    openGroupDialog(row) {
      // 设置额外数据
      this.$refs["updateGroupDialog"].setMeta({
        categoryId: this.selectedCategoryId,
      });
      if (row) {
        this.$refs["updateGroupDialog"].openUpdate(row);
      } else {
        this.$refs["updateGroupDialog"].openSave();
      }
    },
    // 打开属性弹窗
    openAttrDialog(row) {
      // 设置额外数据
      this.$refs["updateAttrDialog"].setMeta({
        groupId: this.selectedGroupId,
      });
      if (row) {
        this.$refs["updateAttrDialog"].openUpdate(row);
      } else {
        this.$refs["updateAttrDialog"].openSave();
      }
    },
    // 商品分类过滤
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 分类树
    remoteCategoryTreeList() {
      productApi.category
        .treeList()
        .then((res) => {
          this.treeData = res.data;
          this.$nextTick(() => {
            this.expandAll();
          });
        })
        .catch((error) => {});
    },
    // 全部展开
    expandAll() {
      for (var i in this.$refs.tree.store.nodesMap) {
        this.$refs.tree.store.nodesMap[i].expanded = true;
      }
    },
    // 清空选中的分组
    clearSelectedGroupInfo() {
      this.selectedGroupId = null;
      this.selectedGroupName = "";
      this.attrTableData = [];
    },
    // 选中分类
    selectedCategory(data, node, tree) {
      // 清空选中的分组
      this.clearSelectedGroupInfo();

      // 获取当前节点所有父级节点
      var parentNodeArr = [];
      var parentNameArr = [];
      this.getParentAll(parentNodeArr, node);
      parentNodeArr.forEach((node, index, arr) => {
        parentNameArr.push(node.data.name);
      });
      parentNameArr.push(data.name);

      // 拼接字符串
      this.selectedCategoryName = parentNameArr.join(" -> ");
      this.remoteGroupList(data.id);
    },
    // 获取当前节点所有父级节点
    getParentAll(parentNodeArr, node) {
      if (node) {
        // 节点的第一个父级
        var parentNode = node.parent;
        // level为节点的层级 level=1 为顶级节点
        for (var j = 0, lv = node.level; j < lv; j++) {
          if (parentNode.level > 0) {
            // 将所有父级节点放入集合中
            parentNodeArr.push(parentNode);
          }
          // 继续获取父级节点的父级节点
          parentNode = parentNode.parent;
        }

        if (parentNodeArr.length > 1) {
          // 如果集合长度>1 则将数组进行倒叙.reverse() 其是就是将所有节点按照 从 顶级节点 依次往下排
          parentNodeArr.reverse();
        }
      }
    },
    // 选中分组
    selectedGroup(row, column, event) {
      this.selectedGroupId = row.id;
      this.selectedGroupName = row.name;
      this.remoteAttrList(row.id);
    },
    // 查询分组列表
    remoteGroupList(categoryId) {
      productApi.group
        .list({ categoryId })
        .then((res) => {
          this.selectedCategoryId = categoryId;
          this.groupTableData = res.data;
          this.selectedGroupId = null;
          this.selectedGroupName = "";
          this.attrTableData = [];
        })
        .catch((error) => {});
    },
    // 查询属性列表
    remoteAttrList(groupId) {
      productApi.baseAttr
        .list(groupId)
        .then((res) => {
          this.selectedGroupId = groupId;
          this.attrTableData = res.data;
        })
        .catch((error) => {});
    },
    // 删除分组
    deleteGroupRow(row) {
      this.$confirm(
        "确认删除" + this.groupDialogTitle + " [ " + row.name + " ] ?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          productApi.group
            .delete(row.id)
            .then((res) => {
              this.resetGroupList();
              this.clearSelectedGroupInfo();
            })
            .catch(() => {});
        })
        .catch(() => {});
    },
    // 删除属性
    deleteAttrRow(row) {
      this.$confirm(
        "确认删除" + this.attrDialogTitle + " [ " + row.name + " ] ?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          productApi.baseAttr
            .delete(row.id)
            .then((res) => {
              this.resetAttrList();
            })
            .catch(() => {});
        })
        .catch(() => {});
    },
  },
  computed: mapState({
    user: (state) => state.user.userInfo,
  }),
};
</script>

<style lang="less" scoped>
.filterInput {
  margin-bottom: 15px;
}
.el-tag {
  height: 40px;
  line-height: 40px;
  font-size: 14px;
}
.el-tree-node__content {
  height: 32px;
}
.options-tag {
  margin-right: 8px;
  height: 36px;
  line-height: 36px;
}
.attrType {
  .el-tag {
    margin-bottom: 5px;
  }
  .el-tag:last-child {
    margin-bottom: 0px;
  }
}
.btnOperateList {
  .el-button {
    margin-right: 10px;
  }
  .el-button:last-child {
    margin-right: 0px;
  }
}
</style>